package com.usoft;

import java.util.ArrayList;
import java.util.List;
import java.util.logging.Logger;

import com.usoft.grpc.example.search.SearchRequest;
import com.usoft.grpc.example.search.SearchResponse;
import com.usoft.grpc.example.search.SearchServiceGrpc;
import io.grpc.stub.StreamObserver;

/**
 * 服务器业务逻辑实现
 * Created by xinxingegeya on 15/9/17.
 */
@SuppressWarnings("Duplicates")
public class SearchServiceImpl implements SearchServiceGrpc.SearchService {

    private static final Logger logger = Logger
        .getLogger(SearchServiceImpl.class.getName());

    /**
     * Simple RPC
     * A simple RPC where the client sends a request to the server using the
     * stub and waits for a response to come back, just like a normal function
     * call.
     * 
     * @param request
     * @param responseObserver
     */
    @Override
    public void searchWithSimpleRpc(SearchRequest request,
            StreamObserver<SearchResponse> responseObserver) {
        System.out.println("pageNo=" + request.getPageNumber());
        System.out.println("query string=" + request.getQuery());
        System.out.println("pageSize=" + request.getResultPerPage());

        List<SearchResponse.Result> results = new ArrayList<SearchResponse.Result>(
            10);

        for (int i = 0; i < request.getResultPerPage(); i++) {
            SearchResponse.Result result = SearchResponse.Result.newBuilder()
                .setTitle("title" + i).setUrl("dev.usoft.com")
                .addSnippets("snippets" + i).build();
            results.add(result);
        }
        SearchResponse response = SearchResponse.newBuilder()
            .addAllResult(results).build();
        responseObserver.onNext(response);
        //We use the response observer's onCompleted() method to specify that we've finished dealing with the RPC.
        responseObserver.onCompleted();
    }
}
